package com.citycloud.ccuap.tc.oauth2.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.tc.common.dto.DataCSecurityBasicUser;
import com.citycloud.ccuap.tc.common.result.ResultObject;
import com.citycloud.ccuap.tc.oauth2.config.CustomerProperties;
import com.citycloud.ccuap.tc.oauth2.dto.UserInfoForSwitchSite;
import com.citycloud.ccuap.tc.oauth2.dto.UserInfoSites;
import com.citycloud.ccuap.tc.oauth2.service.MyClientDetailsService;
import com.citycloud.ccuap.tc.oauth2.service.SiteService;

@Controller
public class SessionBasedSiteController {

	@Autowired
	private SiteService siteService;
	@Autowired
	private MyClientDetailsService myClientDetailsService;

	@Value("${tc.intranet.ip}")
	private String intranetIp;

	/* 获取用户可以切换的站点列表 */
	@RequestMapping(value = { "/sessionBased/siteList" }, method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody ResultObject<UserInfoSites> getSwitchSiteList(Authentication authentication) {
		DataCSecurityBasicUser user = (DataCSecurityBasicUser) authentication.getPrincipal();
		Assert.notNull(user, "当前用户信息不能为空！");
		UserInfoSites userInfoSites = siteService.getSwitchSiteList(user.getUserId(), null, null);
		UserInfoForSwitchSite userInfoForSwitchSite = new UserInfoForSwitchSite(user);
		if (userInfoSites.getUserInfo() != null && userInfoSites.getUserInfo().getPlatformSite() != null) {
			userInfoForSwitchSite.setPlatformSite(userInfoSites.getUserInfo().getPlatformSite());
		}
		userInfoSites.setUserInfo(userInfoForSwitchSite);
		return ResultObject.getInstance().success("获取用户站点列表成功", userInfoSites);
	}

	/** 用户切换站点 */
	@RequestMapping(value = { "/sessionBased/switchSite/{client}/{site}" }, method = { RequestMethod.GET,
			RequestMethod.POST })
	public String switchSite(@PathVariable("client") String clientId, @PathVariable("site") String siteId, String prefixUrl) {
		String redirectUri = getRedirectUrlBySiteId(clientId, prefixUrl);
		String result = "forward:/oauth/authorize?response_type=code&client_id=" + clientId + "&scope=" + siteId;
		result += redirectUri != null ? "&redirect_uri=" + redirectUri + "&state=" + redirectUri : "";
		return result;
	}

	/** 站点管理员访问站点管理页面 */
	@RequestMapping(value = { "/sessionBased/switchSiteManager/{site}/{userId}" }, method = { RequestMethod.GET,
			RequestMethod.POST })
	public String switchSiteManager(@PathVariable("site") String siteId, @PathVariable("userId") Long userId,
			String prefixUrl) {
		AppAssert.notNull(siteId, "请传入site");
		AppAssert.notNull(userId, "请传入userId");

		String redirectUri = getRedirectUrlBySiteId(CustomerProperties.authorizationClientId, prefixUrl);
		String result = "forward:/oauth/authorize?response_type=code&client_id="
				+ CustomerProperties.authorizationClientId + "&scope=" + CustomerProperties.authorizationProjectId;
		if (redirectUri != null) {
			result += "&redirect_uri=" + redirectUri + "&state=" + redirectUri + "," + siteId + "," + userId;
		} else {
			result += "&state=," + siteId + "," + userId;
		}

		return result;
	}

//    @Autowired
//    private Oauth2PermissionService oauth2PermissionService;

	/**
	 * 获取某一个部门下的所有部门以及子部门,若不传部门PID参数则获取所有的部门
	 */
	/*
	 * @RequestMapping( value = {"/getDeptmentsByPid"}, method = {RequestMethod.GET}
	 * )
	 * 
	 * @ResponseBody public com.citycloud.datac.feign.api.result.ResultObject
	 * getDeptmentsByPid(@RequestParam("deptId") String deptId) { return
	 * oauth2PermissionService.getDeptmentsByPid(deptId); }
	 */

	/** 根据clientID查询回调地址，若来源地址和配置内网地址一致，则返回第一个，反之则返回第二个，不考虑超过2个的情况 */
	private String getRedirectUrlBySiteId(String clientId, String prefixUrl) {
		if (StringUtils.isEmpty(prefixUrl)) {
			return null;
		}
		String redirectStr = myClientDetailsService.getWebRedirectByClient(clientId);
		if (StringUtils.isEmpty(redirectStr)) {
			return null;
		} else {
			String[] redirectUrls = redirectStr.split(",");
			if (redirectUrls.length == 1) {
				return null;
			} else {
				if (intranetIp.startsWith(prefixUrl)) {
					return redirectUrls[0];
				} else {
					return redirectUrls[1];
				}
			}
		}
	}
}
